package edu.pitt.dbmi.monarch.rest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.ws.rs.core.Response;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Author : Jeremy Espino MD
 * Created  9/10/13 5:24 PM
 */
public class AbstractRestService {

    protected Gson gson = new GsonBuilder().setPrettyPrinting().create();


    // read java resource into a string
    protected String readResource(String resource) throws IOException {
        StringBuffer sb = new StringBuffer();

        BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(resource), "UTF-8"));
        for (int c = br.read(); c != -1; c = br.read()) sb.append((char) c);

        return sb.toString();
    }

    // create a Json serialized response
    protected Response generateResponse(Object o) {
        String output = gson.toJson(o);
        return Response.status(200).entity(output).build();
    }

    // return a string as a Response
    protected Response generateStringResponse(String s) {

        return Response.status(200).entity(s).build();
    }

    protected String readFile(String file) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = null;
        StringBuilder stringBuilder = new StringBuilder();
        String ls = System.getProperty("line.separator");

        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }

        return stringBuilder.toString();
    }

}
